package com.zyl.mq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author liuwen
 * @Description: rabbitMQ消息发送工具类
 * @Date: 2023/8/24
 */
public class RabbitMQProducer {

    private String queueName;
    private String exchangeName;

    public RabbitMQProducer(String queueName, String exchangeName) {
        this.queueName = queueName;
        this.exchangeName = exchangeName;
    }

    /**
     * 发送消息
     * @param factory
     * @param message
     * @throws Exception
     */
    public void sendMessage(ConnectionFactory factory, String message) throws Exception {
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明队列
            channel.queueDeclare(queueName, false, false, false, null);
            // 声明交换机
            channel.exchangeDeclare(exchangeName, "direct", true);
            // 绑定队列和交换机
            channel.queueBind(queueName, exchangeName, "");
            // 发送消息
            channel.basicPublish(exchangeName, "", null, message.getBytes());
        }
    }
}




